# -*- coding: utf-8 -*-
import os
import tempfile
import uuid

import datetime

import oss2
from flask import Blueprint, jsonify
from flask import render_template
from flask import request

from tank import app
from . import settings

app.config.from_object(settings)

bp = Blueprint('upload', __name__, static_folder='static', template_folder='templates', url_prefix='/upload')


@bp.route("", methods=["POST"])
def upload():
    f = request.files['file']
    ft = request.form.get("fileType")
    now = datetime.datetime.now()
    file_id = str(uuid.uuid4())
    object_name = now.strftime("file/%Y/%m/%d/") + str(uuid.uuid4())
    temppath = os.path.join(tempfile.gettempdir(), file_id)
    f.save(temppath)
    mimetype = f.mimetype
    auth = oss2.Auth(app.config['OSS_KEY'], app.config['OSS_SECRET'])
    bucket = oss2.Bucket(auth, app.config['OSS_HOST'], app.config['OSS_BUCKET'])
    result = bucket.put_object_from_file(object_name, temppath, headers={'Content-Type': mimetype})
    base_url = "http://static.bird01.com"
    if ft.index("image") == 0:
        base_url = "http://image.bird01.com"

    if result.status == 200:
        attach = dict()
        attach['name'] = f.filename
        attach['key'] = object_name
        attach['mimetype'] = mimetype
        attach['server'] = app.config['OSS_HOST']
        attach['size'] = os.path.getsize(temppath)
        attach['url'] = '{}/{}'.format(base_url, attach['key'])
        os.remove(temppath)
        attach['success'] = True
        return jsonify(attach)
    else:
        raise UserWarning("上传文件出错,请重新尝试")


@bp.route("/example")
def upload_example():
    return render_template('upload/index.html')


app.register_blueprint(bp)
